home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / uno.py < prev    next >
Text File  |  2009-10-22  |  13KB  |  362 lines

  1. #*************************************************************************
  2. #
  3. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. # Copyright 2008 by Sun Microsystems, Inc.
  5. #
  6. # OpenOffice.org - a multi-platform office productivity suite
  7. #
  8. # $RCSfile: uno.py,v $
  9. #
  10. # $Revision: 1.9 $
  11. #
  12. # This file is part of OpenOffice.org.
  13. #
  14. # OpenOffice.org is free software: you can redistribute it and/or modify
  15. # it under the terms of the GNU Lesser General Public License version 3
  16. # only, as published by the Free Software Foundation.
  17. #
  18. # OpenOffice.org is distributed in the hope that it will be useful,
  19. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  21. # GNU Lesser General Public License version 3 for more details
  22. # (a copy is included in the LICENSE file that accompanied this code).
  23. #
  24. # You should have received a copy of the GNU Lesser General Public License
  25. # version 3 along with OpenOffice.org.  If not, see
  26. # <http://www.openoffice.org/license.html>
  27. # for a copy of the LGPLv3 License.
  28. #
  29. #*************************************************************************
  30. import os
  31. import sys
  32.  
  33. sys.path.append('/usr/lib/openoffice/basis-link/program')
  34. if getattr(os.environ, 'URE_BOOTSTRAP', None) is None:
  35.     os.environ['URE_BOOTSTRAP'] = "vnd.sun.star.pathname:/usr/lib/openoffice/program/fundamentalrc"
  36.  
  37. import pyuno
  38. import __builtin__
  39. import socket # since on Windows sal3.dll no longer calls WSAStartup
  40.  
  41. # all functions and variables starting with a underscore (_) must be considered private
  42. # and can be changed at any time. Don't use them
  43. _g_ctx = pyuno.getComponentContext( )
  44. _g_delegatee = __builtin__.__dict__["__import__"]
  45.  
  46. def getComponentContext():
  47.     """ returns the UNO component context, that was used to initialize the python runtime.
  48.     """ 
  49.     return _g_ctx      
  50.  
  51. def getConstantByName( constant ):
  52.     "Looks up the value of a idl constant by giving its explicit name"
  53.     return pyuno.getConstantByName( constant )
  54.  
  55. def getTypeByName( typeName):
  56.     """ returns a uno.Type instance of the type given by typeName. In case the
  57.         type does not exist, a com.sun.star.uno.RuntimeException is raised.
  58.     """ 
  59.     return pyuno.getTypeByName( typeName )
  60.  
  61. def createUnoStruct( typeName, *args ):
  62.     """creates a uno struct or exception given by typeName. The parameter args may
  63.     1) be empty. In this case, you get a default constructed uno structure.
  64.        ( e.g. createUnoStruct( "com.sun.star.uno.Exception" ) )
  65.     2) be a sequence with exactly one element, that contains an instance of typeName.
  66.        In this case, a copy constructed instance of typeName is returned
  67.        ( e.g. createUnoStruct( "com.sun.star.uno.Exception" , e ) )
  68.     3) be a sequence, where the length of the sequence must match the number of
  69.        elements within typeName (e.g.
  70.        createUnoStruct( "com.sun.star.uno.Exception", "foo error" , self) ). The
  71.        elements with in the sequence must match the type of each struct element,
  72.        otherwise an exception is thrown.
  73.     """
  74.     return getClass(typeName)( *args )
  75.  
  76. def getClass( typeName ):
  77.     """returns the class of a concrete uno exception, struct or interface
  78.     """
  79.     return pyuno.getClass(typeName)
  80.  
  81. def isInterface( obj ):
  82.     """returns true, when obj is a class of a uno interface"""
  83.     return pyuno.isInterface( obj )
  84.  
  85. def generateUuid():
  86.     "returns a 16 byte sequence containing a newly generated uuid or guid, see rtl/uuid.h "
  87.     return pyuno.generateUuid()        
  88.  
  89. def systemPathToFileUrl( systemPath ):
  90.     "returns a file-url for the given system path"
  91.     return pyuno.systemPathToFileUrl( systemPath )
  92.  
  93. def fileUrlToSystemPath( url ):
  94.     "returns a system path (determined by the system, the python interpreter is running on)"
  95.     return pyuno.fileUrlToSystemPath( url )
  96.  
  97. def absolutize( path, relativeUrl ):
  98.     "returns an absolute file url from the given urls"
  99.     return pyuno.absolutize( path, relativeUrl )
  100.  
  101. def getCurrentContext():
  102.     """Returns the currently valid current context.
  103.        see http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context
  104.        for an explanation on the current context concept
  105.     """
  106.     return pyuno.getCurrentContext()
  107.  
  108. def setCurrentContext( newContext ):
  109.     """Sets newContext as new uno current context. The newContext must
  110.     implement the XCurrentContext interface. The implemenation should
  111.     handle the desired properties and delegate unknown properties to the
  112.     old context. Ensure to reset the old one when you leave your stack ...
  113.     see http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context
  114.     """
  115.     return pyuno.setCurrentContext( newContext )
  116.  
  117.         
  118. class Enum:
  119.     "Represents a UNO idl enum, use an instance of this class to explicitly pass a boolean to UNO" 
  120.     #typeName the name of the enum as a string
  121.     #value    the actual value of this enum as a string
  122.     def __init__(self,typeName, value):
  123.         self.typeName = typeName
  124.         self.value = value
  125.         pyuno.checkEnum( self )
  126.  
  127.     def __repr__(self):
  128.         return "<uno.Enum %s (%r)>" % (self.typeName, self.value)
  129.  
  130.     def __eq__(self, that):
  131.         if not isinstance(that, Enum):
  132.             return False
  133.         return (self.typeName == that.typeName) and (self.value == that.value)
  134.  
  135. class Type:
  136.     "Represents a UNO type, use an instance of this class to explicitly pass a boolean to UNO"
  137. #    typeName                 # Name of the UNO type
  138. #    typeClass                # python Enum of TypeClass,  see com/sun/star/uno/TypeClass.idl
  139.     def __init__(self, typeName, typeClass):
  140.         self.typeName = typeName
  141.         self.typeClass = typeClass
  142.         pyuno.checkType(self)
  143.     def __repr__(self):
  144.         return "<Type instance %s (%r)>" % (self.typeName, self.typeClass)
  145.  
  146.     def __eq__(self, that):
  147.         if not isinstance(that, Type):
  148.             return False
  149.         return self.typeClass == that.typeClass and self.typeName == that.typeName
  150.  
  151.     def __hash__(self):
  152.         return self.typeName.__hash__()
  153.  
  154. class Bool(object):
  155.     """Represents a UNO boolean, use an instance of this class to explicitly 
  156.        pass a boolean to UNO.
  157.        Note: This class is deprecated. Use python's True and False directly instead
  158.     """
  159.     def __new__(cls, value):
  160.         if isinstance(value, (str, unicode)) and value == "true":
  161.             return True
  162.         if isinstance(value, (str, unicode)) and value == "false":
  163.             return False
  164.         if value:
  165.             return True
  166.         return False
  167.  
  168. class Char:
  169.     "Represents a UNO char, use an instance of this class to explicitly pass a char to UNO"
  170.     # @param value pass a Unicode string with length 1
  171.     def __init__(self,value):
  172.         assert isinstance(value, unicode)
  173.         assert len(value) == 1
  174.         self.value=value
  175.  
  176.     def __repr__(self):
  177.         return "<Char instance %s>" % (self.value, )
  178.         
  179.     def __eq__(self, that):
  180.         if isinstance(that, (str, unicode)):
  181.             if len(that) > 1:
  182.                 return False
  183.             return self.value == that[0]
  184.         if isinstance(that, Char):        
  185.             return self.value == that.value
  186.         return False
  187.  
  188. # Suggested by Christian, but still some open problems which need to be solved first
  189. #
  190. #class ByteSequence(str):
  191. #
  192. #    def __repr__(self):
  193. #        return "<ByteSequence instance %s>" % str.__repr__(self)
  194.  
  195.     # for a little bit compatitbility; setting value is not possible as 
  196.     # strings are immutable
  197. #    def _get_value(self):
  198. #        return self
  199. #
  200. #    value = property(_get_value)        
  201.  
  202. class ByteSequence:
  203.     def __init__(self, value):
  204.         if isinstance(value, str):
  205.             self.value = value
  206.         elif isinstance(value, ByteSequence):
  207.             self.value = value.value
  208.         else:
  209.             raise TypeError("expected string or bytesequence")
  210.  
  211.     def __repr__(self):
  212.         return "<ByteSequence instance '%s'>" % (self.value, )
  213.  
  214.     def __eq__(self, that):
  215.         if isinstance( that, ByteSequence):
  216.             return self.value == that.value
  217.         if isinstance(that, str):
  218.             return self.value == that
  219.         return False
  220.  
  221.     def __len__(self):
  222.         return len(self.value)
  223.  
  224.     def __getitem__(self, index):
  225.         return self.value[index]
  226.  
  227.     def __iter__( self ):
  228.         return self.value.__iter__()
  229.  
  230.     def __add__( self , b ):
  231.         if isinstance( b, str ):
  232.             return ByteSequence( self.value + b )
  233.         elif isinstance( b, ByteSequence ):
  234.             return ByteSequence( self.value + b.value )
  235.         raise TypeError( "expected string or ByteSequence as operand" )
  236.  
  237.     def __hash__( self ):
  238.         return self.value.hash()
  239.  
  240.  
  241. class Any:
  242.     "use only in connection with uno.invoke() to pass an explicit typed any"
  243.     def __init__(self, type, value ):
  244.         if isinstance( type, Type ):
  245.             self.type = type
  246.         else:
  247.             self.type = getTypeByName( type )
  248.         self.value = value
  249.  
  250. def invoke( object, methodname, argTuple ):
  251.     "use this function to pass exactly typed anys to the callee (using uno.Any)"
  252.     return pyuno.invoke( object, methodname, argTuple )
  253.     
  254. #---------------------------------------------------------------------------------------
  255. # don't use any functions beyond this point, private section, likely to change
  256. #---------------------------------------------------------------------------------------
  257. #def _uno_import( name, globals={}, locals={}, fromlist=[], level=-1 ):
  258. def _uno_import( name, *optargs, **kwargs ):
  259.     try:
  260. #       print "optargs = " + repr(optargs)
  261.         return _g_delegatee( name, *optargs, **kwargs )
  262.     except ImportError:
  263.         # process optargs
  264.         globals, locals, fromlist = list(optargs)[:3] + [kwargs.get('globals',{}), kwargs.get('locals',{}), kwargs.get('fromlist',[])][len(optargs):]
  265.         if not fromlist:
  266.             raise
  267.     modnames = name.split( "." )
  268.     mod = None
  269.     d = sys.modules
  270.     for x in modnames:
  271.         if d.has_key(x):
  272.            mod = d[x]
  273.         else:
  274.            mod = pyuno.__class__(x)  # How to create a module ??
  275.         d = mod.__dict__
  276.  
  277.     RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
  278.     for x in fromlist:
  279.        if not d.has_key(x):
  280.           if x.startswith( "typeOf" ):
  281.              try: 
  282.                 d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] )
  283.              except RuntimeException,e:
  284.                 raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" )
  285.           else:
  286.             try:
  287.                 # check for structs, exceptions or interfaces
  288.                 d[x] = pyuno.getClass( name + "." + x )
  289.             except RuntimeException,e:
  290.                 # check for enums 
  291.                 try:
  292.                    d[x] = Enum( name , x )
  293.                 except RuntimeException,e2:
  294.                    # check for constants
  295.                    try:
  296.                       d[x] = getConstantByName( name + "." + x )
  297.                    except RuntimeException,e3:
  298.                       # no known uno type !
  299.                       raise ImportError( "type "+ name + "." +x + " is unknown" )
  300.     return mod
  301.  
  302. # hook into the __import__ chain    
  303. __builtin__.__dict__["__import__"] = _uno_import
  304.         
  305. # private function, don't use
  306. def _impl_extractName(name):
  307.     r = range (len(name)-1,0,-1)
  308.     for i in r:
  309.         if name[i] == ".":
  310.            name = name[i+1:len(name)]
  311.            break
  312.     return name            
  313.  
  314. # private, referenced from the pyuno shared library
  315. def _uno_struct__init__(self,*args):
  316.     if len(args) == 1 and hasattr(args[0], "__class__") and args[0].__class__ == self.__class__ :
  317.        self.__dict__["value"] = args[0]
  318.     else:
  319.        self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args)
  320.     
  321. # private, referenced from the pyuno shared library
  322. def _uno_struct__getattr__(self,name):
  323.     return __builtin__.getattr(self.__dict__["value"],name)
  324.  
  325. # private, referenced from the pyuno shared library
  326. def _uno_struct__setattr__(self,name,value):
  327.     return __builtin__.setattr(self.__dict__["value"],name,value)
  328.  
  329. # private, referenced from the pyuno shared library
  330. def _uno_struct__repr__(self):
  331.     return repr(self.__dict__["value"])
  332.     
  333. def _uno_struct__str__(self):
  334.     return str(self.__dict__["value"])
  335.  
  336. # private, referenced from the pyuno shared library
  337. def _uno_struct__eq__(self,cmp):
  338.     if hasattr(cmp,"value"):
  339.        return self.__dict__["value"] == cmp.__dict__["value"]
  340.     return False
  341.  
  342. # referenced from pyuno shared lib and pythonscript.py
  343. def _uno_extract_printable_stacktrace( trace ):
  344.     mod = None
  345.     try:
  346.         mod = __import__("traceback")
  347.     except ImportError,e:
  348.         pass
  349.     ret = ""
  350.     if mod:
  351.         lst = mod.extract_tb( trace )
  352.         max = len(lst)
  353.         for j in range(max):
  354.             i = lst[max-j-1]
  355.             ret = ret + "  " + str(i[0]) + ":" + \
  356.                   str(i[1]) + " in function " + \
  357.                   str(i[2])  + "() [" + str(i[3]) + "]\n"
  358.     else:
  359.         ret = "Couldn't import traceback module"
  360.     return ret
  361.